var http = require('http')
var fs = require('fs')
var until = require('./untils.js')
// querystring是nodejs内置的一个专用于处理url的模块，API只有四个，详情见nodejs官方文档
var querystring = require('querystring')
var server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, {'Content-Type': 'text/html'})
    fs.readFile('./index.html', {encoding: 'utf-8'}, (err, data) => {
      res.end(data)
    })
  } else if (req.url === '/login') {
    // 输出请求体
    if (req.method === 'POST') {
      req.setEncoding('utf-8')
      var body = ''
      req.on('data', chunk => {
        body += chunk
      })
      req.on('end', () => {
        var queryBody = querystring.parse(body)
        res.writeHead(200, {
          'Content-Type': 'application/json',
        })
        res.end(JSON.stringify(queryBody))
      })
    }
  }
  else if (req.url === '/writeResponce') {
    res.setHeader('Content-Type', 'text/html')
    res.end(`<html>
              <body>
                <h1>Hello World</h1>
              </body>
            </html>`)
  }

  else if (req.url === '/upload') {
    if (req.method === 'GET') {
      fs.readFile('./upload.html', {}, (err, data) => {
        res.writeHead(200, {'Content-Type': 'text/html'})
        res.end(data)
      })
    } else {
      // 否则就是提交操作
      var body = ''
      req.on('data', chunk => {
        body += chunk
      })
      req.on('end', () => {
        body = querystring.parse(body)
        console.log(body)
        res.writeHead(200, {'Content-Type': 'application/json'})
        res.end(JSON.stringify(body))
      })
    }
  }
  else if (req.url === '/file') {
    if (req.method === 'GET') {
      fs.readFile('./file.html', {}, (err, data) => {
        res.writeHead(200, {'Content-Type': 'text/html'})
        res.end(data)
      })
    } else {
      until.dealUpload(req, res)
    }
  }
})
server.on('request', (req, res) => {
  // console.log('url', req.url)
  // console.log('method', req.method)
})
server.listen(8080)